<template>
  <div class="recommend-manage-root">
    <!-- 页面标题和说明 -->
    <div class="recommend-header">
      <div class="recommend-title">商品推荐管理</div>
      <div class="recommend-subtitle">推荐位 + 推荐策略分离架构</div>
      <div class="architecture-intro">
        <div class="intro-item">
          <div class="intro-icon">📍</div>
          <div class="intro-text">
            <h4>推荐位（固定）</h4>
            <p>位置固定，样式固定，便于页面布局</p>
          </div>
        </div>
        <div class="intro-item">
          <div class="intro-icon">🎯</div>
          <div class="intro-text">
            <h4>推荐策略（动态）</h4>
            <p>内容动态生成，适应不同用户和场景</p>
          </div>
        </div>
        <div class="intro-item">
          <div class="intro-icon">⚡</div>
          <div class="intro-text">
            <h4>优先级机制</h4>
            <p>高优先级策略覆盖低优先级策略</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 推荐位管理 -->
    <div class="recommend-section">
      <div class="section-header">
        <div class="section-title">
          <h3>推荐位管理</h3>
          <p class="section-desc">管理固定的推荐位置和展示样式</p>
        </div>
        <div class="section-actions">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索推荐位名称"
            style="width: 200px; margin-right: 12px;"
            clearable
          />
          <el-button type="primary" @click="openPositionDialog()">新增推荐位</el-button>
        </div>
      </div>

      <div class="recommend-content">
        <el-table :data="filteredRecommendPositions" border style="width: 100%">
          <el-table-column prop="name" label="推荐位名称" width="180" />
          <el-table-column prop="position" label="推荐位置" width="150">
            <template #default="scope">
              <el-tag type="primary">{{ scope.row.position }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="style" label="展示样式" width="120">
            <template #default="scope">
              <el-tag type="info">{{ scope.row.style }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="maxCount" label="推荐数量" width="100" align="center" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="'enabled'"
                :inactive-value="'disabled'"
                @change="togglePositionStatus(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="320" align="center">
            <template #default="scope">
              <el-button size="small" @click="openPositionDialog(scope.row)">编辑</el-button>
              <el-button size="small" type="success" @click="openStrategyDialog(scope.row)">推荐策略</el-button>
              <el-button size="small" type="warning" @click="openProductDialog(scope.row)">商品配置</el-button>
              <el-button size="small" type="info" @click="openPreviewDialog(scope.row)">预览</el-button>
              <el-button size="small" type="danger" @click="confirmDeletePosition(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 推荐策略管理 -->
    <div class="recommend-section">
      <div class="section-header">
        <div class="section-title">
          <h3>推荐策略管理</h3>
          <p class="section-desc">管理动态的推荐内容生成策略</p>
        </div>
        <div class="section-actions">
          <el-button type="primary" @click="openStrategyDialog()">新增策略</el-button>
        </div>
      </div>

      <div class="recommend-content">
        <el-table :data="recommendStrategies" border style="width: 100%">
          <el-table-column prop="name" label="策略名称" width="180" />
          <el-table-column prop="positionId" label="关联推荐位" width="150">
            <template #default="scope">
              <el-tag type="primary">
                {{ getPositionName(scope.row.positionId) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="策略类型" width="120">
            <template #default="scope">
              <el-tag :type="getStrategyTypeTag(scope.row.type)">
                {{ getStrategyTypeText(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="优先级" width="100" align="center" />
          <el-table-column prop="dataSource" label="数据源" width="120" />
          <el-table-column prop="updateFrequency" label="更新频率" width="120" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="'enabled'"
                :inactive-value="'disabled'"
                @change="toggleStrategyStatus(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="280" align="center">
            <template #default="scope">
              <el-button size="small" @click="openStrategyDialog(scope.row)">编辑</el-button>
              <el-button size="small" type="success" @click="openStrategyConfigDialog(scope.row)">配置</el-button>
              <el-button size="small" type="warning" @click="testStrategy(scope.row)">测试</el-button>
              <el-button size="small" type="danger" @click="confirmDeleteStrategy(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 业务场景演示 -->
    <div class="recommend-section">
      <div class="section-header">
        <div class="section-title">
          <h3>业务场景演示</h3>
          <p class="section-desc">展示推荐位+策略分离架构的实际应用</p>
        </div>
      </div>

      <div class="scenario-demo">
        <div class="scenario-item">
          <div class="scenario-header">
            <h4>场景一：个性化推荐</h4>
            <el-tag type="success">推荐位：首页轮播图</el-tag>
          </div>
          <div class="scenario-content">
            <div class="strategy-list">
              <div class="strategy-item">
                <div class="strategy-info">
                  <span class="strategy-name">个性化推荐策略</span>
                  <span class="strategy-priority">优先级：2</span>
                  <span class="strategy-type">类型：个性化</span>
                </div>
                <div class="strategy-desc">
                  基于用户浏览、收藏、购买行为，动态生成个性化推荐内容
                </div>
              </div>
            </div>
            <div class="demo-result">
              <div class="result-title">推荐结果：</div>
              <div class="result-content">
                <div class="user-scenario">
                  <span class="user-label">用户A（浏览过服装）：</span>
                  <span class="user-result">推荐服装相关商品</span>
                </div>
                <div class="user-scenario">
                  <span class="user-label">用户B（收藏过数码）：</span>
                  <span class="user-result">推荐数码相关商品</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="scenario-item">
          <div class="scenario-header">
            <h4>场景二：活动推荐</h4>
            <el-tag type="warning">推荐位：首页轮播图</el-tag>
          </div>
          <div class="scenario-content">
            <div class="strategy-list">
              <div class="strategy-item">
                <div class="strategy-info">
                  <span class="strategy-name">618活动推荐策略</span>
                  <span class="strategy-priority">优先级：1</span>
                  <span class="strategy-type">类型：活动</span>
                </div>
                <div class="strategy-desc">
                  活动期间覆盖所有用户，显示活动商品，活动结束后恢复个性化推荐
                </div>
              </div>
            </div>
            <div class="demo-result">
              <div class="result-title">推荐结果：</div>
              <div class="result-content">
                <div class="user-scenario">
                  <span class="user-label">活动期间：</span>
                  <span class="user-result">所有用户看到活动商品</span>
                </div>
                <div class="user-scenario">
                  <span class="user-label">活动结束后：</span>
                  <span class="user-result">恢复个性化推荐</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="scenario-item">
          <div class="scenario-header">
            <h4>场景三：热销兜底</h4>
            <el-tag type="info">推荐位：分类页推荐</el-tag>
          </div>
          <div class="scenario-content">
            <div class="strategy-list">
              <div class="strategy-item">
                <div class="strategy-info">
                  <span class="strategy-name">热销商品推荐</span>
                  <span class="strategy-priority">优先级：3</span>
                  <span class="strategy-type">类型：热销</span>
                </div>
                <div class="strategy-desc">
                  当个性化推荐和活动推荐都无法提供足够内容时，显示热销商品作为兜底
                </div>
              </div>
            </div>
            <div class="demo-result">
              <div class="result-title">推荐结果：</div>
              <div class="result-content">
                <div class="user-scenario">
                  <span class="user-label">新用户或无行为数据：</span>
                  <span class="user-result">显示热销商品</span>
                </div>
                <div class="user-scenario">
                  <span class="user-label">个性化数据不足：</span>
                  <span class="user-result">热销商品补充</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 推荐位编辑弹窗 -->
    <el-dialog
      v-model="positionDialogVisible"
      :title="positionEditMode === 'add' ? '新增推荐位' : '编辑推荐位'"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="edit-form">
        <div class="form-item">
          <label>推荐位名称</label>
          <el-input v-model="positionForm.name" placeholder="请输入推荐位名称" />
        </div>
        <div class="form-item">
          <label>推荐位置</label>
          <el-select v-model="positionForm.position" placeholder="请选择推荐位置" style="width: 100%">
            <el-option label="首页轮播图" value="首页轮播图" />
            <el-option label="分类页推荐" value="分类页推荐" />
            <el-option label="详情页相关推荐" value="详情页相关推荐" />
            <el-option label="搜索页推荐" value="搜索页推荐" />
          </el-select>
        </div>
        <div class="form-item">
          <label>展示样式</label>
          <el-select v-model="positionForm.style" placeholder="请选择展示样式" style="width: 100%" @change="handleStyleChange">
            <el-option label="轮播图" value="轮播图" />
            <el-option label="列表" value="列表" />
            <el-option label="网格" value="网格" />
          </el-select>
        </div>
        <div class="form-item" v-if="positionForm.style === '网格'">
          <label>网格列数</label>
          <el-input-number 
            v-model="positionForm.gridColumns" 
            :min="2" 
            :max="5" 
            style="width: 100%"
            placeholder="请设置网格列数"
          />
          <div class="form-tip">设置网格布局的列数，建议2-4列</div>
        </div>
        <div class="form-item">
          <label>推荐数量</label>
          <el-input-number v-model="positionForm.maxCount" :min="1" :max="50" style="width: 100%" />
        </div>
        <div class="form-item">
          <label>状态</label>
          <el-radio-group v-model="positionForm.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">停用</el-radio>
          </el-radio-group>
        </div>
      </div>
      <template #footer>
        <el-button @click="positionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePosition">保存</el-button>
      </template>
    </el-dialog>

    <!-- 推荐策略编辑弹窗 -->
    <el-dialog
      v-model="strategyDialogVisible"
      :title="strategyEditMode === 'add' ? '新增推荐策略' : '编辑推荐策略'"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="edit-form">
        <div class="form-item">
          <label>策略名称</label>
          <el-input v-model="strategyForm.name" placeholder="请输入策略名称" />
        </div>
        <div class="form-item">
          <label>关联推荐位</label>
          <el-select v-model="strategyForm.positionId" placeholder="请选择关联推荐位" style="width: 100%">
            <el-option 
              v-for="position in recommendPositions" 
              :key="position.id" 
              :label="position.name" 
              :value="position.id" 
            />
          </el-select>
        </div>
        <div class="form-item">
          <label>策略类型</label>
          <el-select v-model="strategyForm.type" placeholder="请选择策略类型" style="width: 100%">
            <el-option label="个性化推荐" value="personalized" />
            <el-option label="活动推荐" value="activity" />
            <el-option label="热销推荐" value="hot" />
            <el-option label="手动推荐" value="manual" />
          </el-select>
        </div>
        <div class="form-item">
          <label>优先级</label>
          <el-input-number v-model="strategyForm.priority" :min="1" :max="999" style="width: 100%" />
          <div class="form-tip">数字越小优先级越高，优先级高的策略会覆盖优先级低的策略</div>
        </div>
        <div class="form-item">
          <label>数据源</label>
          <div class="data-source-config">
            <div style="display: flex; gap: 8px; margin-bottom: 12px;">
              <el-select v-model="strategyForm.dataSource" placeholder="请选择数据源" style="flex: 1;">
                <el-option label="用户行为数据" value="user_behavior" />
                <el-option label="活动数据" value="activity_data" />
                <el-option label="热销数据" value="hot_sales" />
                <el-option label="手动配置" value="manual_config" />
              </el-select>
              <el-button size="small" type="info" @click="openDataSourceManage">管理数据源</el-button>
            </div>
            
            <!-- 数据源配置详情 -->
            <div v-if="strategyForm.dataSource" class="data-source-detail">
              <div class="source-info">
                <h5>{{ getDataSourceName(strategyForm.dataSource) }}</h5>
                <p>{{ getDataSourceDesc(strategyForm.dataSource) }}</p>
              </div>
              
              <!-- 用户行为数据配置 -->
              <div v-if="strategyForm.dataSource === 'user_behavior'" class="behavior-config">
                <h6>行为类型配置</h6>
                <el-checkbox-group v-model="strategyForm.behaviorTypes">
                  <el-checkbox label="browse">浏览行为</el-checkbox>
                  <el-checkbox label="purchase">购买行为</el-checkbox>
                  <el-checkbox label="favorite">收藏行为</el-checkbox>
                  <el-checkbox label="cart">加购行为</el-checkbox>
                </el-checkbox-group>
                
                <div class="time-range-config">
                  <h6>时间范围</h6>
                  <el-radio-group v-model="strategyForm.behaviorTimeRange">
                    <el-radio label="7">最近7天</el-radio>
                    <el-radio label="30">最近30天</el-radio>
                    <el-radio label="90">最近90天</el-radio>
                  </el-radio-group>
                </div>
              </div>
              
              <!-- 活动数据配置 -->
              <div v-if="strategyForm.dataSource === 'activity_data'" class="activity-config">
                <h6>活动配置</h6>
                <el-select v-model="strategyForm.activityId" placeholder="选择活动" style="width: 100%; margin-bottom: 8px;">
                  <el-option label="618购物节" value="618" />
                  <el-option label="双11活动" value="1111" />
                  <el-option label="年货节" value="spring" />
                  <el-option label="新品首发" value="new" />
                </el-select>
                
                <div class="activity-priority">
                  <h6>活动优先级</h6>
                  <el-radio-group v-model="strategyForm.activityPriority">
                    <el-radio label="high">高优先级（覆盖其他推荐）</el-radio>
                    <el-radio label="normal">普通优先级</el-radio>
                    <el-radio label="low">低优先级（兜底推荐）</el-radio>
                  </el-radio-group>
                </div>
              </div>
              
              <!-- 热销数据配置 -->
              <div v-if="strategyForm.dataSource === 'hot_sales'" class="hot-config">
                <h6>热销配置</h6>
                <div class="hot-criteria">
                  <el-input-number 
                    v-model="strategyForm.minSales" 
                    :min="1" 
                    placeholder="最小销量"
                    style="width: 100%; margin-bottom: 8px;"
                  />
                  <el-select v-model="strategyForm.hotCategory" placeholder="选择分类" style="width: 100%; margin-bottom: 8px;">
                    <el-option label="全部分类" value="all" />
                    <el-option label="数码产品" value="digital" />
                    <el-option label="服装鞋帽" value="clothing" />
                    <el-option label="家居用品" value="home" />
                  </el-select>
                </div>
              </div>
              
              <!-- 手动配置 -->
              <div v-if="strategyForm.dataSource === 'manual_config'" class="manual-config">
                <h6>手动配置</h6>
                <el-button size="small" type="primary" @click="openManualConfig">选择商品</el-button>
                <div v-if="strategyForm.manualProducts && strategyForm.manualProducts.length > 0" class="selected-products">
                  <p>已选择 {{ strategyForm.manualProducts.length }} 个商品</p>
                </div>
              </div>
              
              <!-- 数据源测试 -->
              <div class="data-source-test">
                <el-button size="small" type="success" @click="testDataSource">测试数据源</el-button>
                <el-button size="small" type="info" @click="previewDataSource">预览数据</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="form-item">
          <label>推荐算法</label>
          <el-select v-model="strategyForm.algorithm" placeholder="请选择推荐算法" style="width: 100%">
            <el-option label="协同过滤" value="collaborative_filtering" />
            <el-option label="内容推荐" value="content_based" />
            <el-option label="规则推荐" value="rule_based" />
          </el-select>
        </div>
        <div class="form-item">
          <label>更新频率</label>
          <el-select v-model="strategyForm.updateFrequency" placeholder="请选择更新频率" style="width: 100%">
            <el-option label="实时更新" value="realtime" />
            <el-option label="每小时更新" value="hourly" />
            <el-option label="每日更新" value="daily" />
          </el-select>
        </div>
        <div class="form-item">
          <label>状态</label>
          <el-radio-group v-model="strategyForm.status">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">停用</el-radio>
          </el-radio-group>
        </div>
      </div>
      <template #footer>
        <el-button @click="strategyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStrategy">保存</el-button>
      </template>
    </el-dialog>

    <!-- 商品配置弹窗 -->
    <el-dialog
      v-model="productDialogVisible"
      title="商品配置"
      width="900px"
      :close-on-click-modal="false"
    >
      <div class="product-config">
        <div class="config-header">
          <div class="config-info">
            <h4>{{ currentRecommend?.name }}</h4>
            <p>推荐位：{{ currentRecommend?.position }} | 样式：{{ currentRecommend?.style }}</p>
          </div>
          <div class="config-actions">
            <el-button size="small" @click="openProductSelector">添加商品</el-button>
            <el-button size="small" type="warning" @click="openBatchImportDialog">批量导入</el-button>
            <el-button size="small" type="info" @click="openBatchSettingsDialog">批量设置</el-button>
          </div>
        </div>

        <el-table 
          :data="currentProducts" 
          border 
          style="width: 100%"
          @selection-change="handleProductSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="productName" label="商品名称" width="200" />
          <el-table-column prop="productImage" label="商品图片" width="100">
            <template #default="scope">
              <img :src="scope.row.productImage" style="width: 50px; height: 50px; object-fit: cover;" />
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" width="100">
            <template #default="scope">
              ¥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="sort" label="排序" width="100" align="center" />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="'enabled'"
                :inactive-value="'disabled'"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="scope">
              <el-button size="small" type="danger" @click="removeProduct(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div style="margin-top: 16px;">
          <el-button size="small" type="danger" @click="batchDeleteProducts">批量删除</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 商品选择器弹窗 -->
    <el-dialog
      v-model="productSelectorVisible"
      title="选择商品"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="product-selector">
        <div class="selector-search">
          <el-input
            v-model="productSearchKeyword"
            placeholder="搜索商品名称"
            style="width: 200px; margin-right: 12px;"
            clearable
          />
          <el-select v-model="productCategory" placeholder="选择分类" style="width: 150px; margin-right: 12px;">
            <el-option label="全部" value="" />
            <el-option label="数码" value="digital" />
            <el-option label="服装" value="clothing" />
          </el-select>
          <el-button type="primary" @click="searchProducts">搜索</el-button>
        </div>

        <div class="product-grid">
          <div
            v-for="product in filteredProductList"
            :key="product.id"
            class="product-item"
            :class="{ selected: selectedProducts.includes(product.id) }"
            @click="toggleProductSelection(product.id)"
          >
            <img :src="product.image" :alt="product.name" />
            <div class="product-info">
              <div class="product-name">{{ product.name }}</div>
              <div class="product-price">¥{{ product.price }}</div>
            </div>
            <div class="product-check">
              <el-icon v-if="selectedProducts.includes(product.id)">
                <Check />
              </el-icon>
            </div>
          </div>
        </div>

        <div class="selector-footer">
          <div class="selected-count">已选择 {{ selectedProducts.length }} 个商品</div>
          <div class="selector-actions">
            <el-button @click="productSelectorVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmAddProducts">确认添加</el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 预览弹窗 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="H5移动端预览"
      width="900px"
      :close-on-click-modal="false"
    >
      <div class="h5-preview-container">
        <div class="preview-header">
          <div class="preview-info">
            <h4>{{ currentRecommend?.name }}</h4>
            <p>推荐位：{{ currentRecommend?.position }} | 样式：{{ currentRecommend?.style }}</p>
          </div>
          <div class="preview-actions">
            <el-button size="small" @click="refreshPreview">刷新</el-button>
            <el-button 
              v-if="currentRecommend?.style === '轮播图'" 
              size="small" 
              @click="toggleAutoPlay"
            >
              {{ isAutoPlaying ? '停止' : '自动播放' }}
            </el-button>
          </div>
        </div>

        <div class="mobile-preview">
          <div 
            class="mobile-frame"
            @touchstart="handlePullStart"
            @touchmove="handlePullMove"
            @touchend="handlePullEnd"
          >
            <!-- 下拉刷新指示器 -->
            <div class="pull-refresh-indicator">
              <div class="refresh-icon">🔄</div>
              <div class="refresh-text">下拉刷新</div>
            </div>
            
            <!-- 轮播图样式预览 -->
            <div v-if="currentRecommend?.style === '轮播图'" class="mobile-carousel">
              <div 
                class="carousel-container"
                @touchstart="handleTouchStart"
                @touchend="handleTouchEnd"
              >
                <div 
                  v-for="(product, index) in previewProducts" 
                  :key="product.id"
                  class="carousel-item"
                  :class="{ active: index === currentCarouselIndex }"
                >
                  <img :src="product.productImage" :alt="product.productName" />
                  <div class="carousel-overlay">
                    <h3>{{ product.productName }}</h3>
                    <p class="price">¥{{ product.price }}</p>
                  </div>
                </div>
              </div>
              <div class="carousel-dots">
                <span
                  v-for="(product, index) in previewProducts"
                  :key="index"
                  class="dot"
                  :class="{ active: index === currentCarouselIndex }"
                  @click="currentCarouselIndex = index"
                ></span>
              </div>
            </div>

            <!-- 列表样式预览 -->
            <div v-else-if="currentRecommend?.style === '列表'" class="mobile-list">
              <div 
                v-for="product in previewProducts" 
                :key="product.id"
                class="list-item"
                :data-product-id="product.id"
                @touchstart="handleTouchStart"
                @touchend="handleTouchEnd"
                @click="handleDoubleTap"
              >
                <img :src="product.productImage" :alt="product.productName" />
                <div class="item-content">
                  <h4>{{ product.productName }}</h4>
                  <p class="price">¥{{ product.price }}</p>
                  <p class="sort">排序：{{ product.sort }}</p>
                </div>
              </div>
            </div>

            <!-- 网格样式预览 -->
            <div v-else-if="currentRecommend?.style === '网格'" class="mobile-grid" :style="getGridStyle()">
              <div 
                v-for="product in previewProducts" 
                :key="product.id"
                class="grid-item"
                :data-product-id="product.id"
                @touchstart="handleTouchStart"
                @touchend="handleTouchEnd"
                @click="handleDoubleTap"
              >
                <img :src="product.productImage" :alt="product.productName" />
                <div class="item-content">
                  <h4>{{ product.productName }}</h4>
                  <p class="price">¥{{ product.price }}</p>
                </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-if="previewProducts.length === 0" class="empty-preview">
              <div class="empty-icon">📦</div>
              <h3>暂无商品</h3>
              <p>请先添加商品到推荐位</p>
            </div>
          </div>
        </div>

        <div class="preview-footer">
          <div class="preview-stats">
            共 {{ previewProducts.length }} 个商品
          </div>
          <div class="mobile-tips">
            <p>💡 移动端操作提示：</p>
            <ul>
              <li>👆 点击商品查看详情</li>
              <li>👆👆 双击商品快速操作</li>
              <li>👆 长按商品显示更多信息</li>
              <li>⬅️➡️ 轮播图支持左右滑动</li>
              <li>⬇️ 下拉刷新推荐内容</li>
            </ul>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 批量导入弹窗 -->
    <el-dialog
      v-model="batchImportDialogVisible"
      title="批量导入商品"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="batch-import">
        <div class="import-methods">
          <el-radio-group v-model="importMethod">
            <el-radio label="excel">Excel导入</el-radio>
            <el-radio label="ids">商品ID导入</el-radio>
            <el-radio label="category">分类导入</el-radio>
          </el-radio-group>
        </div>

        <!-- Excel导入 -->
        <div v-if="importMethod === 'excel'" class="excel-import">
          <el-upload
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
            accept=".xlsx,.xls,.csv"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持 .xlsx, .xls, .csv 格式文件
              </div>
            </template>
          </el-upload>
          <div class="template-download">
            <el-button size="small" @click="downloadTemplate">下载模板</el-button>
          </div>
        </div>

        <!-- 商品ID导入 -->
        <div v-if="importMethod === 'ids'" class="ids-import">
          <el-input
            v-model="productIdsText"
            type="textarea"
            :rows="6"
            placeholder="请输入商品ID，每行一个"
          />
          <div class="import-tips">
            <p>导入说明：</p>
            <ul>
              <li>每行输入一个商品ID</li>
              <li>支持批量导入多个商品</li>
              <li>系统会自动匹配商品信息</li>
            </ul>
          </div>
        </div>

        <!-- 分类导入 -->
        <div v-if="importMethod === 'category'" class="category-import">
          <el-select v-model="importCategory" placeholder="选择商品分类" style="width: 100%; margin-bottom: 10px;">
            <el-option label="数码" value="digital" />
            <el-option label="服装" value="clothing" />
            <el-option label="家居" value="home" />
          </el-select>
          <el-input-number 
            v-model="importCount" 
            :min="1" 
            :max="100" 
            placeholder="导入数量"
            style="width: 100%; margin-bottom: 10px;"
          />
          <el-select v-model="importSortBy" placeholder="排序方式" style="width: 100%;">
            <el-option label="销量" value="sales" />
            <el-option label="价格" value="price" />
            <el-option label="评分" value="rating" />
          </el-select>
        </div>

        <div class="import-preview">
          <p>预览：将导入 {{ importMethod === 'excel' ? 'Excel文件中的商品' : 
                          importMethod === 'ids' ? (productIdsText.split('\n').filter(id => id.trim()).length + '个商品') : 
                          importCount + '个' + importCategory + '分类商品' }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="batchImportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchImport">确认导入</el-button>
      </template>
    </el-dialog>

    <!-- 批量设置弹窗 -->
    <el-dialog
      v-model="batchSettingsDialogVisible"
      title="批量设置"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="batch-settings">
        <div class="settings-section">
          <h4>设置范围</h4>
          <el-radio-group v-model="batchTarget">
            <el-radio label="selected">选中商品</el-radio>
            <el-radio label="all">全部商品</el-radio>
          </el-radio-group>
          <div v-if="batchTarget === 'selected'" class="selected-count">
            已选择 {{ selectedProductIds.length }} 个商品
          </div>
        </div>

        <div class="settings-section">
          <h4>设置项目</h4>
          <el-checkbox-group v-model="batchSettings">
            <el-checkbox label="sort">排序</el-checkbox>
            <el-checkbox label="status">状态</el-checkbox>
          </el-checkbox-group>
        </div>

        <div v-if="batchSettings.includes('sort')" class="settings-section">
          <h4>排序设置</h4>
          <div class="sort-settings">
            <el-radio-group v-model="sortMethod">
              <el-radio label="fixed">固定值</el-radio>
              <el-radio label="increment">递增</el-radio>
              <el-radio label="random">随机</el-radio>
            </el-radio-group>
            <div class="setting-input">
              <el-input-number 
                v-if="sortMethod === 'fixed'" 
                v-model="fixedSortValue" 
                :min="1" 
                placeholder="固定值"
              />
              <template v-if="sortMethod === 'increment'">
                <el-input-number v-model="incrementStartValue" :min="1" placeholder="起始值" />
                <el-input-number v-model="incrementStep" :min="1" placeholder="步长" />
              </template>
            </div>
          </div>
        </div>

        <div v-if="batchSettings.includes('status')" class="settings-section">
          <h4>状态设置</h4>
          <el-radio-group v-model="batchStatus">
            <el-radio label="enabled">启用</el-radio>
            <el-radio label="disabled">停用</el-radio>
          </el-radio-group>
        </div>
      </div>
      <template #footer>
        <el-button @click="batchSettingsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmBatchSettings">确认设置</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="400px"
    >
      <p>确定要删除推荐位"{{ recommendToDelete?.name }}"吗？</p>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="doDeleteRecommend">确认删除</el-button>
      </template>
    </el-dialog>

    <!-- 数据源管理弹窗 -->
    <el-dialog
      v-model="dataSourceManageVisible"
      title="数据源管理"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="data-source-manage">
        <div class="ds-tabs">
          <el-tabs v-model="activeDataSourceTab">
            <el-tab-pane label="用户行为数据" name="user_behavior">
              <div class="ds-content">
                <h4>用户行为数据配置</h4>
                <p>基于用户的实际行为数据，为用户推荐个性化商品。</p>
                
                <div class="ds-config-section">
                  <h5>数据来源</h5>
                  <el-checkbox-group v-model="userBehaviorConfig.sources">
                    <el-checkbox label="browse">浏览记录</el-checkbox>
                    <el-checkbox label="purchase">购买记录</el-checkbox>
                    <el-checkbox label="favorite">收藏记录</el-checkbox>
                    <el-checkbox label="cart">加购记录</el-checkbox>
                    <el-checkbox label="search">搜索记录</el-checkbox>
                  </el-checkbox-group>
                </div>
                
                <div class="ds-config-section">
                  <h5>时间权重</h5>
                  <el-radio-group v-model="userBehaviorConfig.timeWeight">
                    <el-radio label="recent">最近行为权重更高</el-radio>
                    <el-radio label="equal">所有行为权重相等</el-radio>
                    <el-radio label="decay">时间衰减权重</el-radio>
                  </el-radio-group>
                </div>
                
                <div class="ds-config-section">
                  <h5>推荐算法</h5>
                  <el-select v-model="userBehaviorConfig.algorithm" style="width: 100%">
                    <el-option label="协同过滤" value="collaborative" />
                    <el-option label="内容推荐" value="content" />
                    <el-option label="深度学习" value="deep_learning" />
                  </el-select>
                </div>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="活动数据" name="activity_data">
              <div class="ds-content">
                <h4>活动数据配置</h4>
                <p>根据当前活动规则，推荐活动相关商品。</p>
                
                <div class="ds-config-section">
                  <h5>活动列表</h5>
                  <div style="margin-bottom: 12px;">
                    <el-button size="small" type="primary" @click="openActivityCreate">创建活动</el-button>
                    <el-button size="small" type="info" @click="syncActivityData">同步活动数据</el-button>
                  </div>
                  <el-table :data="activityList" border style="width: 100%">
                    <el-table-column prop="name" label="活动名称" />
                    <el-table-column prop="startDate" label="开始时间" />
                    <el-table-column prop="endDate" label="结束时间" />
                    <el-table-column prop="status" label="状态">
                      <template #default="scope">
                        <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
                          {{ scope.row.status === 'active' ? '进行中' : '已结束' }}
                        </el-tag>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                      <template #default="scope">
                        <el-button size="small" @click="editActivity(scope.row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteActivity(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
                
                <div class="ds-config-section">
                  <h5>活动优先级</h5>
                  <p>当多个活动同时进行时，优先级高的活动会覆盖优先级低的活动。</p>
                  <el-radio-group v-model="activityConfig.priority">
                    <el-radio label="high">高优先级（覆盖其他推荐）</el-radio>
                    <el-radio label="normal">普通优先级</el-radio>
                    <el-radio label="low">低优先级（兜底推荐）</el-radio>
                  </el-radio-group>
                </div>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="热销数据" name="hot_sales">
              <div class="ds-content">
                <h4>热销数据配置</h4>
                <p>基于商品销量、热度等数据，推荐热门商品。</p>
                
                <div class="ds-config-section">
                  <h5>热销指标</h5>
                  <el-checkbox-group v-model="hotSalesConfig.metrics">
                    <el-checkbox label="sales">销量</el-checkbox>
                    <el-checkbox label="views">浏览量</el-checkbox>
                    <el-checkbox label="favorites">收藏数</el-checkbox>
                    <el-checkbox label="rating">评分</el-checkbox>
                  </el-checkbox-group>
                </div>
                
                <div class="ds-config-section">
                  <h5>时间范围</h5>
                  <el-radio-group v-model="hotSalesConfig.timeRange">
                    <el-radio label="7">最近7天</el-radio>
                    <el-radio label="30">最近30天</el-radio>
                    <el-radio label="90">最近90天</el-radio>
                  </el-radio-group>
                </div>
                
                <div class="ds-config-section">
                  <h5>分类筛选</h5>
                  <el-select v-model="hotSalesConfig.category" placeholder="选择分类" style="width: 100%">
                    <el-option label="全部分类" value="all" />
                    <el-option label="数码产品" value="digital" />
                    <el-option label="服装鞋帽" value="clothing" />
                    <el-option label="家居用品" value="home" />
                  </el-select>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <template #footer>
        <el-button @click="dataSourceManageVisible = false">取消</el-button>
        <el-button type="primary" @click="saveDataSourceConfig">保存配置</el-button>
      </template>
    </el-dialog>

    <!-- 活动创建/编辑弹窗 -->
    <el-dialog
      v-model="activityDialogVisible"
      :title="activityEditMode === 'add' ? '创建活动' : '编辑活动'"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="activity-form">
        <div class="form-item">
          <label>活动名称</label>
          <el-input v-model="activityForm.name" placeholder="请输入活动名称" />
        </div>
        
        <div class="form-item">
          <label>活动类型</label>
          <el-select v-model="activityForm.type" placeholder="请选择活动类型" style="width: 100%">
            <el-option label="促销活动" value="promotion" />
            <el-option label="节日活动" value="festival" />
            <el-option label="新品首发" value="new_product" />
            <el-option label="限时优惠" value="limited_time" />
            <el-option label="会员专享" value="member_only" />
          </el-select>
        </div>
        
        <div class="form-item">
          <label>活动时间</label>
          <el-date-picker
            v-model="activityForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 100%"
          />
        </div>
        
        <div class="form-item">
          <label>活动商品</label>
          <div class="activity-products">
            <el-button size="small" type="primary" @click="selectActivityProducts">选择商品</el-button>
            <div v-if="activityForm.products && activityForm.products.length > 0" class="selected-products-list">
              <p>已选择 {{ activityForm.products.length }} 个商品</p>
              <el-tag 
                v-for="product in activityForm.products.slice(0, 3)" 
                :key="product.id"
                size="small"
                style="margin-right: 4px; margin-bottom: 4px;"
              >
                {{ product.name }}
              </el-tag>
              <span v-if="activityForm.products.length > 3" style="color: #999; font-size: 12px;">
                等 {{ activityForm.products.length }} 个商品
              </span>
            </div>
          </div>
        </div>
        
        <div class="form-item">
          <label>推荐规则</label>
          <el-radio-group v-model="activityForm.recommendRule">
            <el-radio label="all">推荐所有活动商品</el-radio>
            <el-radio label="hot">仅推荐热门活动商品</el-radio>
            <el-radio label="new">仅推荐新品活动商品</el-radio>
            <el-radio label="custom">自定义推荐规则</el-radio>
          </el-radio-group>
        </div>
        
        <div class="form-item">
          <label>优先级</label>
          <el-input-number 
            v-model="activityForm.priority" 
            :min="1" 
            :max="10"
            style="width: 100%"
          />
          <div class="form-tip">优先级越高，在推荐中的权重越大</div>
        </div>
        
        <div class="form-item">
          <label>活动状态</label>
          <el-switch v-model="activityForm.status" />
          <span style="margin-left: 8px; color: #666;">{{ activityForm.status ? '启用' : '禁用' }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="activityDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveActivity">保存活动</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { Check } from '@element-plus/icons-vue'

// 推荐位数据结构（固定位置和样式）
interface RecommendPosition {
  id: string
  name: string
  position: string // 推荐位置：首页轮播图、分类页推荐、详情页相关推荐等
  style: string // 展示样式：轮播图、列表、网格
  gridColumns?: number // 网格列数
  maxCount: number // 最大推荐数量
  status: 'enabled' | 'disabled'
  createTime: string
  updateTime: string
}

// 推荐策略数据结构（动态内容生成）
interface RecommendStrategy {
  id: string
  name: string
  positionId: string // 关联的推荐位ID
  type: 'personalized' | 'activity' | 'hot' | 'manual' // 策略类型：个性化、活动、热销、手动
  priority: number // 优先级，数字越小优先级越高
  status: 'enabled' | 'disabled'
  dataSource: string // 数据源：user_behavior, activity_data, hot_sales, manual_config
  algorithm: string // 推荐算法：collaborative_filtering, content_based, rule_based
  updateFrequency: string // 更新频率：realtime, hourly, daily
  conditions: RecommendCondition[] // 推荐条件
  timeRange?: TimeRange // 时间范围
  userGroup?: UserGroup // 用户群体
  behaviorRules?: BehaviorRule[] // 行为规则
  logicOperator: 'AND' | 'OR'
  createTime: string
  updateTime: string
}

// 推荐条件
interface RecommendCondition {
  field: string
  operator: string
  value: any
}

// 时间范围
interface TimeRange {
  startTime: string
  endTime: string
  daysOfWeek: number[]
  isEnabled: boolean
}

// 用户群体
interface UserGroup {
  type: 'all' | 'new' | 'vip' | 'active' | 'custom'
  customRules?: UserCondition[]
}

// 用户条件
interface UserCondition {
  field: string
  operator: string
  value: any
}

// 行为规则
interface BehaviorRule {
  type: 'browse' | 'purchase' | 'favorite' | 'cart'
  condition: string
  value: number
  timeRange: number // 天数
}

// 推荐商品数据结构
interface RecommendProduct {
  id: string
  productId: string
  productName: string
  productImage: string
  price: number
  sort: number
  status: 'enabled' | 'disabled'
  strategyId: string // 关联的策略ID
  priority?: number
}

// 商品数据结构
interface Product {
  id: string
  name: string
  price: number
  image: string
  category: string
}

// 推荐位列表（mock数据）
const recommendPositions = ref<RecommendPosition[]>([
  {
    id: '1',
    name: '首页轮播图',
    position: '首页轮播图',
    style: '轮播图',
    maxCount: 5,
    status: 'enabled',
    createTime: '2024-01-15 10:30:00',
    updateTime: '2024-01-15 10:30:00'
  },
  {
    id: '2',
    name: '分类页推荐',
    position: '分类页推荐',
    style: '网格',
    gridColumns: 3,
    maxCount: 10,
    status: 'enabled',
    createTime: '2024-01-14 14:20:00',
    updateTime: '2024-01-14 14:20:00'
  },
  {
    id: '3',
    name: '详情页相关推荐',
    position: '详情页相关推荐',
    style: '列表',
    maxCount: 8,
    status: 'disabled',
    createTime: '2024-01-13 09:15:00',
    updateTime: '2024-01-13 09:15:00'
  },
  {
    id: '4',
    name: '搜索页推荐',
    position: '搜索页推荐',
    style: '网格',
    gridColumns: 2,
    maxCount: 6,
    status: 'enabled',
    createTime: '2024-01-12 16:45:00',
    updateTime: '2024-01-12 16:45:00'
  }
])

// 推荐策略列表（mock数据）
const recommendStrategies = ref<RecommendStrategy[]>([
  {
    id: 's1',
    name: '个性化推荐策略',
    positionId: '1',
    type: 'personalized',
    priority: 2,
    status: 'enabled',
    dataSource: 'user_behavior',
    algorithm: 'collaborative_filtering',
    updateFrequency: 'realtime',
    conditions: [
      { field: 'category', operator: 'eq', value: 'digital' }
    ],
    logicOperator: 'AND',
    timeRange: {
      startTime: '09:00',
      endTime: '22:00',
      daysOfWeek: [1, 2, 3, 4, 5, 6, 7],
      isEnabled: false
    },
    userGroup: {
      type: 'all'
    },
    behaviorRules: [
      {
        type: 'browse',
        condition: 'gt',
        value: 3,
        timeRange: 7
      }
    ],
    createTime: '2024-01-15 10:30:00',
    updateTime: '2024-01-15 10:30:00'
  },
  {
    id: 's2',
    name: '618活动推荐策略',
    positionId: '1',
    type: 'activity',
    priority: 1,
    status: 'enabled',
    dataSource: 'activity_data',
    algorithm: 'rule_based',
    updateFrequency: 'daily',
    conditions: [
      { field: 'activity', operator: 'eq', value: '618' }
    ],
    logicOperator: 'AND',
    timeRange: {
      startTime: '00:00',
      endTime: '23:59',
      daysOfWeek: [1, 2, 3, 4, 5, 6, 7],
      isEnabled: true
    },
    userGroup: {
      type: 'all'
    },
    behaviorRules: [],
    createTime: '2024-01-14 14:20:00',
    updateTime: '2024-01-14 14:20:00'
  },
  {
    id: 's3',
    name: '热销商品推荐',
    positionId: '2',
    type: 'hot',
    priority: 3,
    status: 'enabled',
    dataSource: 'hot_sales',
    algorithm: 'rule_based',
    updateFrequency: 'hourly',
    conditions: [
      { field: 'sales', operator: 'gt', value: '1000' }
    ],
    logicOperator: 'AND',
    timeRange: {
      startTime: '09:00',
      endTime: '22:00',
      daysOfWeek: [1, 2, 3, 4, 5, 6, 7],
      isEnabled: false
    },
    userGroup: {
      type: 'all'
    },
    behaviorRules: [],
    createTime: '2024-01-13 09:15:00',
    updateTime: '2024-01-13 09:15:00'
  }
])

// 推荐商品数据（mock数据）
const recommendProducts = ref<Record<string, RecommendProduct[]>>({
  's1': [
    {
      id: '1',
      productId: 'p1',
      productName: 'iPhone 15 Pro',
      productImage: 'https://via.placeholder.com/100x100/007AFF/FFFFFF?text=iPhone',
      price: 7999,
      sort: 1,
      status: 'enabled',
      strategyId: 's1'
    },
    {
      id: '2',
      productId: 'p2',
      productName: 'MacBook Pro 14',
      productImage: 'https://via.placeholder.com/100x100/34C759/FFFFFF?text=MacBook',
      price: 14999,
      sort: 2,
      status: 'enabled',
      strategyId: 's1'
    }
  ],
  's2': [
    {
      id: '3',
      productId: 'p3',
      productName: '618活动商品1',
      productImage: 'https://via.placeholder.com/100x100/FF3B30/FFFFFF?text=618-1',
      price: 599,
      sort: 1,
      status: 'enabled',
      strategyId: 's2'
    },
    {
      id: '4',
      productId: 'p4',
      productName: '618活动商品2',
      productImage: 'https://via.placeholder.com/100x100/FF9500/FFFFFF?text=618-2',
      price: 899,
      sort: 2,
      status: 'enabled',
      strategyId: 's2'
    }
  ],
  's3': [
    {
      id: '5',
      productId: 'p5',
      productName: '热销商品1',
      productImage: 'https://via.placeholder.com/100x100/5856D6/FFFFFF?text=Hot-1',
      price: 299,
      sort: 1,
      status: 'enabled',
      strategyId: 's3'
    }
  ]
})

// 商品列表（mock数据）
const productList = ref<Product[]>([
  {
    id: 'p1',
    name: 'iPhone 15 Pro',
    price: 7999,
    image: 'https://via.placeholder.com/100x100/007AFF/FFFFFF?text=iPhone',
    category: 'digital'
  },
  {
    id: 'p2',
    name: 'MacBook Pro 14',
    price: 14999,
    image: 'https://via.placeholder.com/100x100/34C759/FFFFFF?text=MacBook',
    category: 'digital'
  },
  {
    id: 'p3',
    name: 'Nike Air Max',
    price: 899,
    image: 'https://via.placeholder.com/100x100/FF3B30/FFFFFF?text=Nike',
    category: 'clothing'
  },
  {
    id: 'p4',
    name: 'Adidas Ultraboost',
    price: 1299,
    image: 'https://via.placeholder.com/100x100/000000/FFFFFF?text=Adidas',
    category: 'clothing'
  },
  {
    id: 'p5',
    name: '小米13 Ultra',
    price: 5999,
    image: 'https://via.placeholder.com/100x100/FF6B35/FFFFFF?text=Xiaomi',
    category: 'digital'
  },
  {
    id: 'p6',
    name: '华为 Mate 60 Pro',
    price: 6999,
    image: 'https://via.placeholder.com/100x100/FF0000/FFFFFF?text=Huawei',
    category: 'digital'
  }
])

// 搜索关键词
const searchKeyword = ref('')

// 过滤后的推荐位列表
const filteredRecommendPositions = computed(() => {
  if (!searchKeyword.value) return recommendPositions.value
  return recommendPositions.value.filter(item => 
    item.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 获取推荐位关联的策略
const getStrategiesByPosition = (positionId: string) => {
  return recommendStrategies.value.filter(strategy => strategy.positionId === positionId)
}

// 获取策略类型标签
const getStrategyTypeTag = (type: string) => {
  const typeMap: Record<string, string> = {
    'personalized': 'primary',
    'activity': 'success',
    'hot': 'warning',
    'manual': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取策略类型文本
const getStrategyTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'personalized': '个性化',
    'activity': '活动',
    'hot': '热销',
    'manual': '手动'
  }
  return typeMap[type] || type
}

// 获取推荐位名称
const getPositionName = (positionId: string) => {
  const position = recommendPositions.value.find(p => p.id === positionId)
  return position ? position.name : '未知推荐位'
}

// 获取数据源名称
const getDataSourceName = (dataSource: string) => {
  const nameMap: Record<string, string> = {
    'user_behavior': '用户行为数据',
    'activity_data': '活动数据',
    'hot_sales': '热销数据',
    'manual_config': '手动配置'
  }
  return nameMap[dataSource] || dataSource
}

// 获取数据源描述
const getDataSourceDesc = (dataSource: string) => {
  const descMap: Record<string, string> = {
    'user_behavior': '基于用户浏览、购买、收藏等行为数据，为用户推荐个性化商品',
    'activity_data': '根据当前活动规则，推荐活动相关商品，支持优先级设置',
    'hot_sales': '基于商品销量、热度等数据，推荐热门商品作为兜底',
    'manual_config': '管理员手动选择商品进行推荐，适用于特殊场景'
  }
  return descMap[dataSource] || '暂无描述'
}

// 打开手动配置弹窗
const openManualConfig = () => {
  // 这里可以打开商品选择器
  alert('打开商品选择器进行手动配置')
}

// 测试数据源
const testDataSource = () => {
  const dataSource = strategyForm.value.dataSource
  if (!dataSource) {
    alert('请先选择数据源')
    return
  }
  
  // 模拟测试数据源
  alert(`正在测试数据源：${getDataSourceName(dataSource)}\n\n测试结果：\n✅ 数据源连接正常\n✅ 数据格式正确\n✅ 推荐算法可用`)
}

// 预览数据源
const previewDataSource = () => {
  const dataSource = strategyForm.value.dataSource
  if (!dataSource) {
    alert('请先选择数据源')
    return
  }
  
  // 模拟预览数据
  const mockData = {
    'user_behavior': [
      { name: 'iPhone 15 Pro', score: 0.95, reason: '用户经常浏览数码产品' },
      { name: 'MacBook Pro', score: 0.88, reason: '用户购买过同类产品' },
      { name: 'AirPods Pro', score: 0.82, reason: '用户收藏过相关商品' }
    ],
    'activity_data': [
      { name: '618活动商品1', score: 1.0, reason: '活动期间优先推荐' },
      { name: '618活动商品2', score: 0.95, reason: '活动商品' },
      { name: '618活动商品3', score: 0.90, reason: '活动商品' }
    ],
    'hot_sales': [
      { name: '热销商品1', score: 0.85, reason: '销量排名第1' },
      { name: '热销商品2', score: 0.80, reason: '销量排名第2' },
      { name: '热销商品3', score: 0.75, reason: '销量排名第3' }
    ],
    'manual_config': [
      { name: '手动商品1', score: 1.0, reason: '手动配置' },
      { name: '手动商品2', score: 1.0, reason: '手动配置' },
      { name: '手动商品3', score: 1.0, reason: '手动配置' }
    ]
  }
  
  const data = mockData[dataSource as keyof typeof mockData] || []
  const dataText = data.map(item => 
    `${item.name} (推荐分数: ${item.score}, 原因: ${item.reason})`
  ).join('\n')
  
  alert(`数据源预览：${getDataSourceName(dataSource)}\n\n推荐商品：\n${dataText}`)
}

// 保存数据源配置
const saveDataSourceConfig = () => {
  // 保存各种数据源的配置
  console.log('保存数据源配置:', {
    userBehavior: userBehaviorConfig.value,
    activity: activityConfig.value,
    hotSales: hotSalesConfig.value
  })
  
  alert('数据源配置已保存！')
  dataSourceManageVisible.value = false
}

// 打开数据源管理
const openDataSourceManage = () => {
  dataSourceManageVisible.value = true
}

// 活动管理相关函数
const openActivityCreate = () => {
  activityEditMode.value = 'add'
  activityForm.value = {
    id: '',
    name: '',
    type: 'promotion',
    dateRange: [],
    products: [],
    recommendRule: 'all',
    priority: 5,
    status: true
  }
  activityDialogVisible.value = true
}

const syncActivityData = () => {
  // 模拟同步活动数据
  alert('正在同步活动数据...\n\n✅ 已同步 3 个活动\n✅ 活动商品数据已更新\n✅ 推荐规则已同步')
}

const editActivity = (activity: any) => {
  activityEditMode.value = 'edit'
  activityForm.value = {
    id: activity.id,
    name: activity.name,
    type: activity.type || 'promotion',
    dateRange: [activity.startDate, activity.endDate],
    products: activity.products || [],
    recommendRule: 'all',
    priority: activity.priority || 5,
    status: activity.status === 'active'
  }
  activityDialogVisible.value = true
}

const deleteActivity = (activity: any) => {
  if (confirm(`确定要删除活动"${activity.name}"吗？`)) {
    const index = activityList.value.findIndex(item => item.id === activity.id)
    if (index > -1) {
      activityList.value.splice(index, 1)
      alert('活动删除成功！')
    }
  }
}

const selectActivityProducts = () => {
  // 打开商品选择器
  alert('打开商品选择器，选择活动商品')
}

const saveActivity = () => {
  if (!activityForm.value.name) {
    alert('请输入活动名称')
    return
  }
  
  if (!activityForm.value.dateRange || activityForm.value.dateRange.length !== 2) {
    alert('请选择活动时间')
    return
  }
  
  const activityData = {
    id: activityForm.value.id || Date.now().toString(),
    name: activityForm.value.name,
    type: activityForm.value.type,
    startDate: activityForm.value.dateRange[0],
    endDate: activityForm.value.dateRange[1],
    status: activityForm.value.status ? 'active' : 'inactive',
    priority: activityForm.value.priority,
    products: activityForm.value.products,
    recommendRule: activityForm.value.recommendRule
  }
  
  if (activityEditMode.value === 'add') {
    activityList.value.push(activityData)
  } else {
    const index = activityList.value.findIndex(item => item.id === activityForm.value.id)
    if (index > -1) {
      activityList.value[index] = activityData
    }
  }
  
  alert('活动保存成功！')
  activityDialogVisible.value = false
}

// 获取推荐位关联的商品
const getProductsByPosition = (positionId: string) => {
  const strategies = getStrategiesByPosition(positionId)
  const allProducts: RecommendProduct[] = []
  
  strategies.forEach(strategy => {
    const products = recommendProducts.value[strategy.id] || []
    allProducts.push(...products)
  })
  
  return allProducts
}

// 切换推荐位状态
const togglePositionStatus = (position: RecommendPosition) => {
  position.updateTime = new Date().toLocaleString()
}

// 切换策略状态
const toggleStrategyStatus = (strategy: RecommendStrategy) => {
  strategy.updateTime = new Date().toLocaleString()
}

// 打开推荐位编辑弹窗
const openPositionDialog = (position?: RecommendPosition) => {
  if (position) {
    positionEditMode.value = 'edit'
    positionForm.value = { ...position }
  } else {
    positionEditMode.value = 'add'
    positionForm.value = {
      name: '',
      position: '',
      maxCount: 1,
      style: '',
      gridColumns: 2,
      status: 'enabled'
    }
  }
  positionDialogVisible.value = true
}

// 保存推荐位
const savePosition = () => {
  if (!positionForm.value.name) {
    alert('请输入推荐位名称')
    return
  }
  if (!positionForm.value.position) {
    alert('请选择推荐位置')
    return
  }
  if (!positionForm.value.style) {
    alert('请选择展示样式')
    return
  }

  if (positionEditMode.value === 'add') {
    const newPosition: RecommendPosition = {
      id: Date.now().toString(),
      name: positionForm.value.name,
      position: positionForm.value.position,
      maxCount: positionForm.value.maxCount || 1,
      style: positionForm.value.style,
      gridColumns: positionForm.value.style === '网格' ? positionForm.value.gridColumns : undefined,
      status: positionForm.value.status || 'enabled',
      createTime: new Date().toLocaleString(),
      updateTime: new Date().toLocaleString()
    }
    recommendPositions.value.push(newPosition)
  } else {
    const index = recommendPositions.value.findIndex(item => item.id === positionForm.value.id)
    if (index > -1) {
      recommendPositions.value[index] = {
        ...recommendPositions.value[index],
        ...positionForm.value,
        gridColumns: positionForm.value.style === '网格' ? positionForm.value.gridColumns : undefined,
        updateTime: new Date().toLocaleString()
      }
    }
  }
  positionDialogVisible.value = false
}

// 打开策略编辑弹窗
const openStrategyDialog = (strategy?: RecommendStrategy) => {
  if (strategy) {
    strategyEditMode.value = 'edit'
    strategyForm.value = { ...strategy }
  } else {
    strategyEditMode.value = 'add'
    strategyForm.value = {
      name: '',
      positionId: '',
      type: 'personalized',
      priority: 1,
      status: 'enabled',
      dataSource: 'user_behavior',
      algorithm: 'collaborative_filtering',
      updateFrequency: 'realtime',
      conditions: [],
      logicOperator: 'AND',
      timeRange: {
        startTime: '09:00',
        endTime: '22:00',
        daysOfWeek: [1, 2, 3, 4, 5, 6, 7],
        isEnabled: false
      },
      userGroup: {
        type: 'all'
      },
      behaviorRules: []
    }
  }
  strategyDialogVisible.value = true
}

// 保存推荐策略
const saveStrategy = () => {
  if (!strategyForm.value.name) {
    alert('请输入策略名称')
    return
  }
  if (!strategyForm.value.positionId) {
    alert('请选择关联推荐位')
    return
  }
  if (!strategyForm.value.type) {
    alert('请选择策略类型')
    return
  }

  if (strategyEditMode.value === 'add') {
    const newStrategy: RecommendStrategy = {
      id: Date.now().toString(),
      name: strategyForm.value.name,
      positionId: strategyForm.value.positionId,
      type: strategyForm.value.type,
      priority: strategyForm.value.priority || 1,
      status: strategyForm.value.status || 'enabled',
      dataSource: strategyForm.value.dataSource || 'user_behavior',
      algorithm: strategyForm.value.algorithm || 'collaborative_filtering',
      updateFrequency: strategyForm.value.updateFrequency || 'realtime',
      conditions: strategyForm.value.conditions || [],
      logicOperator: strategyForm.value.logicOperator || 'AND',
      timeRange: strategyForm.value.timeRange,
      userGroup: strategyForm.value.userGroup,
      behaviorRules: strategyForm.value.behaviorRules || [],
      createTime: new Date().toLocaleString(),
      updateTime: new Date().toLocaleString()
    }
    recommendStrategies.value.push(newStrategy)
  } else {
    const index = recommendStrategies.value.findIndex(item => item.id === strategyForm.value.id)
    if (index > -1) {
      recommendStrategies.value[index] = {
        ...recommendStrategies.value[index],
        ...strategyForm.value,
        updateTime: new Date().toLocaleString()
      }
    }
  }
  strategyDialogVisible.value = false
}

// 打开策略配置弹窗
const openStrategyConfigDialog = (strategy: RecommendStrategy) => {
  // 实现策略配置逻辑
  console.log('打开策略配置弹窗', strategy)
  // 这里可以打开一个更详细的策略配置弹窗
  // 包含条件设置、时间范围、用户群体、行为规则等
}

// 测试策略
const testStrategy = (strategy: RecommendStrategy) => {
  // 实现策略测试逻辑
  console.log('测试策略', strategy)
  // 这里可以模拟策略执行，显示测试结果
  alert(`正在测试策略：${strategy.name}`)
}

// 确认删除推荐位
const confirmDeletePosition = (position: RecommendPosition) => {
  if (confirm(`确定要删除推荐位"${position.name}"吗？`)) {
    const index = recommendPositions.value.findIndex(item => item.id === position.id)
    if (index > -1) {
      recommendPositions.value.splice(index, 1)
      // 同时删除相关的策略和商品
      recommendStrategies.value = recommendStrategies.value.filter(s => s.positionId !== position.id)
      delete recommendProducts.value[position.id]
    }
  }
}

// 确认删除策略
const confirmDeleteStrategy = (strategy: RecommendStrategy) => {
  if (confirm(`确定要删除策略"${strategy.name}"吗？`)) {
    const index = recommendStrategies.value.findIndex(item => item.id === strategy.id)
    if (index > -1) {
      recommendStrategies.value.splice(index, 1)
      // 删除相关的商品
      delete recommendProducts.value[strategy.id]
    }
  }
}

// 推荐位编辑弹窗相关
const positionDialogVisible = ref(false)
const positionEditMode = ref<'add' | 'edit'>('add')
const positionForm = ref<Partial<RecommendPosition>>({
  name: '',
  position: '',
  maxCount: 1,
  style: '',
  gridColumns: 2,
  status: 'enabled'
})

// 推荐策略编辑弹窗相关
const strategyDialogVisible = ref(false)
const strategyEditMode = ref<'add' | 'edit'>('add')
const strategyForm = ref<Partial<RecommendStrategy> & {
  behaviorTypes?: string[]
  behaviorTimeRange?: string
  activityId?: string
  activityPriority?: string
  minSales?: number
  hotCategory?: string
  manualProducts?: any[]
}>({
  name: '',
  positionId: '',
  type: 'personalized',
  priority: 1,
  status: 'enabled',
  dataSource: 'user_behavior',
  algorithm: 'collaborative_filtering',
  updateFrequency: 'realtime',
  conditions: [],
  logicOperator: 'AND',
  timeRange: {
    startTime: '09:00',
    endTime: '22:00',
    daysOfWeek: [1, 2, 3, 4, 5, 6, 7],
    isEnabled: false
  },
  userGroup: {
    type: 'all'
  },
  behaviorRules: [],
  behaviorTypes: ['browse', 'purchase'],
  behaviorTimeRange: '30',
  activityId: '',
  activityPriority: 'normal',
  minSales: 100,
  hotCategory: 'all',
  manualProducts: []
})

// 编辑弹窗相关（保留兼容性）
const editDialogVisible = ref(false)
const editMode = ref<'add' | 'edit'>('add')
const editForm = ref<Partial<RecommendPosition>>({
  name: '',
  position: '',
  style: '',
  gridColumns: 2,
  status: 'enabled'
})

// 删除弹窗相关
const deleteDialogVisible = ref(false)
const recommendToDelete = ref<RecommendPosition | null>(null)

// 商品配置弹窗相关
const productDialogVisible = ref(false)
const currentRecommend = ref<RecommendPosition | null>(null)
const currentProducts = ref<RecommendProduct[]>([])

// 商品选择器弹窗相关
const productSelectorVisible = ref(false)
const productSearchKeyword = ref('')
const productCategory = ref('')
const selectedProducts = ref<string[]>([])

// 预览弹窗相关
const previewDialogVisible = ref(false)
const previewProducts = ref<RecommendProduct[]>([])
const currentCarouselIndex = ref(0)
const isAutoPlaying = ref(false)

// 批量导入弹窗相关
const batchImportDialogVisible = ref(false)
const importMethod = ref('excel') // 'excel' | 'ids' | 'category'
const fileList = ref<any[]>([])
const productIdsText = ref('')
const importCategory = ref('')
const importCount = ref(10)
const importSortBy = ref('sales')

// 批量设置弹窗相关
const batchSettingsDialogVisible = ref(false)
const batchTarget = ref('selected') // 'selected' | 'all'
const batchSettings = ref<string[]>([]) // ['sort', 'status', 'priority']
const sortMethod = ref('fixed') // 'fixed' | 'increment' | 'random'
const fixedSortValue = ref(1)
const incrementStartValue = ref(1)
const incrementStep = ref(1)
const batchStatus = ref('enabled') // 'enabled' | 'disabled'
const batchPriority = ref(1)

// 数据源管理相关
const dataSourceManageVisible = ref(false)
const activeDataSourceTab = ref('user_behavior')

// 用户行为数据配置
const userBehaviorConfig = ref({
  sources: ['browse', 'purchase'],
  timeWeight: 'recent',
  algorithm: 'collaborative'
})

// 活动配置
const activityConfig = ref({
  priority: 'normal'
})

// 热销数据配置
const hotSalesConfig = ref({
  metrics: ['sales', 'views'],
  timeRange: '30',
  category: 'all'
})

// 活动列表
const activityList = ref<Array<{
  id: string
  name: string
  startDate: string
  endDate: string
  status: string
  type: string
  priority: number
  products: any[]
}>>([
  {
    id: '1',
    name: '618购物节',
    startDate: '2024-06-01',
    endDate: '2024-06-18',
    status: 'active',
    type: 'promotion',
    priority: 8,
    products: []
  },
  {
    id: '2',
    name: '双11活动',
    startDate: '2024-11-01',
    endDate: '2024-11-11',
    status: 'inactive',
    type: 'promotion',
    priority: 9,
    products: []
  },
  {
    id: '3',
    name: '年货节',
    startDate: '2024-01-15',
    endDate: '2024-02-15',
    status: 'inactive',
    type: 'festival',
    priority: 7,
    products: []
  }
])

// 活动创建/编辑相关
const activityDialogVisible = ref(false)
const activityEditMode = ref<'add' | 'edit'>('add')
const activityForm = ref<{
  id: string
  name: string
  type: string
  dateRange: any[]
  products: any[]
  recommendRule: string
  priority: number
  status: boolean
}>({
  id: '',
  name: '',
  type: 'promotion',
  dateRange: [],
  products: [],
  recommendRule: 'all',
  priority: 5,
  status: true
})

// 批量删除商品
const selectedProductIds = ref<string[]>([])

// 过滤后的商品列表
const filteredProductList = computed(() => {
  let filtered = productList.value
  
  if (productSearchKeyword.value) {
    filtered = filtered.filter(item => 
      item.name.toLowerCase().includes(productSearchKeyword.value.toLowerCase())
    )
  }
  
  if (productCategory.value) {
    filtered = filtered.filter(item => item.category === productCategory.value)
  }
  
  return filtered
})

// 处理样式变化
function handleStyleChange() {
  // 当样式不是网格时，重置网格列数
  if (positionForm.value.style !== '网格') {
    positionForm.value.gridColumns = undefined
  } else if (!positionForm.value.gridColumns) {
    // 当选择网格样式且没有设置列数时，设置默认值
    positionForm.value.gridColumns = 2
  }
}

// 打开编辑弹窗
function openEditDialog(recommend?: RecommendPosition) {
  if (recommend) {
    editMode.value = 'edit'
    editForm.value = { ...recommend }
  } else {
    editMode.value = 'add'
    editForm.value = {
      name: '',
      position: '',
      style: '',
      gridColumns: 2,
      status: 'enabled'
    }
  }
  editDialogVisible.value = true
}

// 保存推荐位
function saveRecommend() {
  if (!editForm.value.name) {
    alert('请输入推荐位名称')
    return
  }
  if (!editForm.value.position) {
    alert('请选择推荐位置')
    return
  }
  if (!editForm.value.style) {
    alert('请选择展示样式')
    return
  }

  if (editMode.value === 'add') {
    const newRecommend: RecommendPosition = {
      id: Date.now().toString(),
      name: editForm.value.name,
      position: editForm.value.position,
      style: editForm.value.style,
      gridColumns: editForm.value.style === '网格' ? editForm.value.gridColumns : undefined,
      maxCount: editForm.value.maxCount || 10,
      status: editForm.value.status || 'enabled',
      createTime: new Date().toLocaleString(),
      updateTime: new Date().toLocaleString()
    }
    recommendPositions.value.push(newRecommend)
  } else {
    const index = recommendPositions.value.findIndex(item => item.id === editForm.value.id)
    if (index > -1) {
      recommendPositions.value[index] = {
        ...recommendPositions.value[index],
        ...editForm.value,
        gridColumns: editForm.value.style === '网格' ? editForm.value.gridColumns : undefined,
        updateTime: new Date().toLocaleString()
      }
    }
  }
  editDialogVisible.value = false
}

// 确认删除
function confirmDelete(recommend: RecommendPosition) {
  recommendToDelete.value = recommend
  deleteDialogVisible.value = true
}

// 执行删除
function doDeleteRecommend() {
  if (recommendToDelete.value) {
    const index = recommendPositions.value.findIndex(item => item.id === recommendToDelete.value?.id)
    if (index > -1) {
      recommendPositions.value.splice(index, 1)
    }
  }
  deleteDialogVisible.value = false
  recommendToDelete.value = null
}

// 切换状态
function toggleStatus(recommend: RecommendPosition) {
  recommend.updateTime = new Date().toLocaleString()
}

// 打开商品配置弹窗
function openProductDialog(recommend: RecommendPosition) {
  currentRecommend.value = recommend
  currentProducts.value = recommendProducts.value[recommend.id] || []
  productDialogVisible.value = true
}

// 打开商品选择器
function openProductSelector() {
  selectedProducts.value = []
  productSearchKeyword.value = ''
  productCategory.value = ''
  productSelectorVisible.value = true
}

// 搜索商品
function searchProducts() {
  // 实际项目中这里会调用API
  console.log('搜索商品:', productSearchKeyword.value, productCategory.value)
}

// 切换商品选择
function toggleProductSelection(productId: string) {
  const index = selectedProducts.value.indexOf(productId)
  if (index > -1) {
    selectedProducts.value.splice(index, 1)
  } else {
    selectedProducts.value.push(productId)
  }
}

// 确认添加商品
function confirmAddProducts() {
  if (!currentRecommend.value) return
  
  const newProducts: RecommendProduct[] = selectedProducts.value.map((productId, index) => {
    const product = productList.value.find(p => p.id === productId)
    if (!product) return null
    
    return {
      id: Date.now().toString() + index,
      productId: product.id,
      productName: product.name,
      productImage: product.image,
      price: product.price,
      sort: (currentProducts.value.length + index + 1),
      status: 'enabled' as const,
      strategyId: currentRecommend.value!.id
    }
  }).filter(Boolean) as RecommendProduct[]
  
  if (!recommendProducts.value[currentRecommend.value.id]) {
    recommendProducts.value[currentRecommend.value.id] = []
  }
  
  recommendProducts.value[currentRecommend.value.id].push(...newProducts)
  currentProducts.value = recommendProducts.value[currentRecommend.value.id]
  
  productSelectorVisible.value = false
  selectedProducts.value = []
}

// 移除商品
function removeProduct(product: RecommendProduct) {
  if (!currentRecommend.value) return
  
  const index = currentProducts.value.findIndex(p => p.id === product.id)
  if (index > -1) {
    currentProducts.value.splice(index, 1)
    recommendProducts.value[currentRecommend.value.id] = currentProducts.value
  }
}

function handleProductSelectionChange(selection: RecommendProduct[]) {
  selectedProductIds.value = selection.map(item => item.id)
}

function batchDeleteProducts() {
  if (selectedProductIds.value.length === 0) {
    alert('请先选择要删除的商品')
    return
  }
  
  if (!currentRecommend.value) return
  
  if (confirm(`确定要删除选中的 ${selectedProductIds.value.length} 个商品吗？`)) {
    currentProducts.value = currentProducts.value.filter(
      product => !selectedProductIds.value.includes(product.id)
    )
    recommendProducts.value[currentRecommend.value.id] = currentProducts.value
    selectedProductIds.value = []
  }
}

// 更新商品排序
function updateProductSort(product: RecommendProduct) {
  if (!currentRecommend.value) return
  
  // 重新排序
  currentProducts.value.sort((a, b) => a.sort - b.sort)
  recommendProducts.value[currentRecommend.value.id] = currentProducts.value
}

// 获取行样式类名
function getRowClassName({ row, rowIndex }: { row: RecommendProduct; rowIndex: number }) {
  return `product-row-${rowIndex}`
}

// 拖拽排序相关
function handleDragStart(event: DragEvent, product: RecommendProduct) {
  if (event.dataTransfer) {
    event.dataTransfer.setData('text/plain', product.id)
    event.dataTransfer.effectAllowed = 'move'
  }
}

function handleDragOver(event: DragEvent) {
  event.preventDefault()
  event.dataTransfer!.dropEffect = 'move'
}

function handleDrop(event: DragEvent, targetProduct: RecommendProduct) {
  event.preventDefault()
  const sourceId = event.dataTransfer!.getData('text/plain')
  const sourceIndex = currentProducts.value.findIndex(p => p.id === sourceId)
  const targetIndex = currentProducts.value.findIndex(p => p.id === targetProduct.id)
  
  if (sourceIndex !== -1 && targetIndex !== -1 && sourceIndex !== targetIndex) {
    // 重新排序
    const sourceProduct = currentProducts.value[sourceIndex]
    currentProducts.value.splice(sourceIndex, 1)
    currentProducts.value.splice(targetIndex, 0, sourceProduct)
    
    // 更新排序权重
    currentProducts.value.forEach((product, index) => {
      product.sort = index + 1
    })
    
    if (currentRecommend.value) {
      recommendProducts.value[currentRecommend.value.id] = currentProducts.value
    }
  }
}

// 打开推荐预览弹窗
function openPreviewDialog(recommend: RecommendPosition) {
  currentRecommend.value = recommend
  previewProducts.value = recommendProducts.value[recommend.id] || []
  currentCarouselIndex.value = 0
  previewDialogVisible.value = true
  
  // 如果是轮播图样式，启动自动轮播
  if (recommend.style === '轮播图' && previewProducts.value.length > 1) {
    startCarouselAutoPlay()
  }
}

// 刷新预览
function refreshPreview() {
  // 刷新预览逻辑，例如重新获取商品列表或重新计算排序
  // 这里简单地重新设置 currentCarouselIndex 为 0 表示刷新
  currentCarouselIndex.value = 0
  
  // 重新启动轮播
  if (currentRecommend.value?.style === '轮播图' && previewProducts.value.length > 1) {
    startCarouselAutoPlay()
  }
}

// 轮播图自动播放
let carouselTimer: number | null = null

function startCarouselAutoPlay() {
  // 清除之前的定时器
  if (carouselTimer) {
    clearInterval(carouselTimer)
  }
  
  // 设置新的定时器，每3秒切换一次
  carouselTimer = setInterval(() => {
    if (previewProducts.value.length > 1) {
      currentCarouselIndex.value = (currentCarouselIndex.value + 1) % previewProducts.value.length
    }
  }, 3000)
  
  isAutoPlaying.value = true
}

// 移动端触摸滑动支持
let touchStartX = 0
let touchEndX = 0
let longPressTimer: number | null = null

function handleTouchStart(event: TouchEvent) {
  touchStartX = event.touches[0].clientX
  
  // 长按检测
  longPressTimer = setTimeout(() => {
    const target = event.target as HTMLElement
    const productId = target.closest('.grid-item, .list-item')?.getAttribute('data-product-id')
    if (productId) {
      showProductDetail(productId)
    }
  }, 800)
}

function handleTouchEnd(event: TouchEvent) {
  touchEndX = event.changedTouches[0].clientX
  
  // 清除长按定时器
  if (longPressTimer) {
    clearTimeout(longPressTimer)
    longPressTimer = null
  }
  
  handleSwipe()
}

function handleSwipe() {
  const swipeThreshold = 50
  const diff = touchStartX - touchEndX
  
  if (Math.abs(diff) > swipeThreshold) {
    if (diff > 0) {
      // 向左滑动，下一张
      if (previewProducts.value.length > 1) {
        currentCarouselIndex.value = (currentCarouselIndex.value + 1) % previewProducts.value.length
      }
    } else {
      // 向右滑动，上一张
      if (previewProducts.value.length > 1) {
        currentCarouselIndex.value = currentCarouselIndex.value === 0 
          ? previewProducts.value.length - 1 
          : currentCarouselIndex.value - 1
      }
    }
  }
}

// 显示商品详情
function showProductDetail(productId: string) {
  const product = previewProducts.value.find(p => p.id === productId)
  if (product) {
    alert(`商品详情：\n名称：${product.productName}\n价格：¥${product.price}\n排序：${product.sort}\n状态：${product.status}`)
  }
}

// 移动端下拉刷新模拟
let pullStartY = 0
let pullDistance = 0

// 双击检测
let lastTapTime = 0

function handlePullStart(event: TouchEvent) {
  pullStartY = event.touches[0].clientY
}

function handleDoubleTap(event: MouseEvent) {
  const currentTime = new Date().getTime()
  const tapLength = currentTime - lastTapTime
  
  if (tapLength < 500 && tapLength > 0) {
    // 双击事件
    const target = event.target as HTMLElement
    const productId = target.closest('.grid-item, .list-item')?.getAttribute('data-product-id')
    if (productId) {
      quickAction(productId)
    }
  }
  
  lastTapTime = currentTime
}

function quickAction(productId: string) {
  const product = previewProducts.value.find(p => p.id === productId)
  if (product) {
    const action = prompt(`快速操作：\n1. 查看详情\n2. 调整排序\n3. 切换状态\n\n请选择操作：`, '1')
    
    switch (action) {
      case '1':
        showProductDetail(productId)
        break
      case '2':
        const newSort = prompt('请输入新的排序值：', product.sort.toString())
        if (newSort && !isNaN(Number(newSort))) {
          product.sort = Number(newSort)
          // 模拟震动反馈
          simulateVibration()
        }
        break
      case '3':
        product.status = product.status === 'enabled' ? 'disabled' : 'enabled'
        // 模拟震动反馈
        simulateVibration()
        break
    }
  }
}

// 模拟震动反馈
function simulateVibration() {
  // 在真实移动端，这里会调用 navigator.vibrate(100)
  console.log('震动反馈')
  
  // 添加视觉反馈
  const mobileFrame = document.querySelector('.mobile-frame') as HTMLElement
  if (mobileFrame) {
    mobileFrame.style.transform = 'scale(0.98)'
    setTimeout(() => {
      mobileFrame.style.transform = 'scale(1)'
    }, 100)
  }
}

function handlePullMove(event: TouchEvent) {
  const currentY = event.touches[0].clientY
  pullDistance = currentY - pullStartY
  
  if (pullDistance > 0) {
    // 显示下拉刷新指示器
    const indicator = document.querySelector('.pull-refresh-indicator') as HTMLElement
    if (indicator) {
      indicator.style.transform = `translateY(${Math.min(pullDistance, 80)}px)`
    }
  }
}

function handlePullEnd() {
  if (pullDistance > 80) {
    // 触发刷新
    refreshPreview()
  }
  
  // 重置下拉状态
  pullDistance = 0
  const indicator = document.querySelector('.pull-refresh-indicator') as HTMLElement
  if (indicator) {
    indicator.style.transform = 'translateY(0)'
  }
}

// 获取网格样式
function getGridStyle() {
  if (currentRecommend.value?.style === '网格' && currentRecommend.value?.gridColumns) {
    const columns = currentRecommend.value.gridColumns
    return {
      'grid-template-columns': `repeat(${columns}, 1fr)`
    }
  }
  return {
    'grid-template-columns': 'repeat(2, 1fr)' // 默认2列
  }
}

// 停止轮播图自动播放
function stopCarouselAutoPlay() {
  if (carouselTimer) {
    clearInterval(carouselTimer)
    carouselTimer = null
  }
  isAutoPlaying.value = false
}

// 切换轮播图自动播放
function toggleAutoPlay() {
  if (isAutoPlaying.value) {
    stopCarouselAutoPlay()
  } else {
    startCarouselAutoPlay()
  }
}

// 批量导入相关
function handleFileChange(file: any) {
  fileList.value = file ? [file] : []
}

function downloadTemplate() {
  const template = `商品ID,商品名称,商品价格,商品分类,商品图片URL\n` +
                    `p1,iPhone 15 Pro,7999,digital,https://via.placeholder.com/100x100/007AFF/FFFFFF?text=iPhone\n` +
                    `p2,MacBook Pro 14,14999,digital,https://via.placeholder.com/100x100/34C759/FFFFFF?text=MacBook\n` +
                    `p3,Nike Air Max,899,clothing,https://via.placeholder.com/100x100/FF3B30/FFFFFF?text=Nike`
  const blob = new Blob([template], { type: 'text/csv' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = '商品导入模板.csv'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)
}

// 打开批量导入弹窗
function openBatchImportDialog() {
  batchImportDialogVisible.value = true
  importMethod.value = 'excel'
  fileList.value = []
  productIdsText.value = ''
  importCategory.value = ''
  importCount.value = 10
  importSortBy.value = 'sales'
}

// 批量导入确认
function confirmBatchImport() {
  if (!currentRecommend.value) {
    alert('请先选择推荐位')
    return
  }
  if (importMethod.value === 'excel') {
    // 这里只做模拟，实际应解析Excel
    // 假设导入2个商品
    const newProducts = [
      {
        id: Date.now().toString() + 'e1',
        productId: 'excel1',
        productName: 'Excel商品1',
        productImage: 'https://via.placeholder.com/100x100/007AFF/FFFFFF?text=Excel1',
        price: 100,
        sort: currentProducts.value.length + 1,
        status: 'enabled' as const,
        strategyId: currentRecommend.value!.id
      },
      {
        id: Date.now().toString() + 'e2',
        productId: 'excel2',
        productName: 'Excel商品2',
        productImage: 'https://via.placeholder.com/100x100/34C759/FFFFFF?text=Excel2',
        price: 200,
        sort: currentProducts.value.length + 2,
        status: 'enabled' as const,
        strategyId: currentRecommend.value!.id
      }
    ]
    if (!recommendProducts.value[currentRecommend.value.id]) {
      recommendProducts.value[currentRecommend.value.id] = []
    }
    recommendProducts.value[currentRecommend.value.id].push(...newProducts)
    currentProducts.value = recommendProducts.value[currentRecommend.value.id]
    alert('模拟Excel导入成功！')
  } else if (importMethod.value === 'ids') {
    if (!productIdsText.value) {
      alert('请输入商品ID')
      return
    }
    const ids = productIdsText.value.split('\n').map(id => id.trim()).filter(id => id)
    if (ids.length === 0) {
      alert('请输入有效的商品ID')
      return
    }
    const newProducts = ids.map((id, idx) => ({
      id: Date.now().toString() + id,
      productId: id,
      productName: `导入商品${id}`,
      productImage: 'https://via.placeholder.com/100x100/FF3B30/FFFFFF?text=' + id,
      price: 99 + idx,
      sort: currentProducts.value.length + idx + 1,
      status: 'enabled' as const,
      strategyId: currentRecommend.value!.id
    }))
    if (!recommendProducts.value[currentRecommend.value.id]) {
      recommendProducts.value[currentRecommend.value.id] = []
    }
    recommendProducts.value[currentRecommend.value.id].push(...newProducts)
    currentProducts.value = recommendProducts.value[currentRecommend.value.id]
    alert(`成功导入${ids.length}个商品！`)
  } else if (importMethod.value === 'category') {
    if (!importCategory.value) {
      alert('请选择商品分类')
      return
    }
    if (!importCount.value) {
      alert('请输入导入数量')
      return
    }
    // 模拟导入指定分类的商品
    const newProducts = Array.from({ length: importCount.value }, (_, idx) => ({
      id: Date.now().toString() + importCategory.value + idx,
      productId: importCategory.value + idx,
      productName: `${importCategory.value}商品${idx + 1}`,
      productImage: 'https://via.placeholder.com/100x100/000000/FFFFFF?text=' + importCategory.value + (idx + 1),
      price: 50 + idx,
      sort: currentProducts.value.length + idx + 1,
      status: 'enabled' as const,
      strategyId: currentRecommend.value!.id
    }))
    if (!recommendProducts.value[currentRecommend.value.id]) {
      recommendProducts.value[currentRecommend.value.id] = []
    }
    recommendProducts.value[currentRecommend.value.id].push(...newProducts)
    currentProducts.value = recommendProducts.value[currentRecommend.value.id]
    alert(`成功导入${importCount.value}个商品！`)
  }
  batchImportDialogVisible.value = false
  fileList.value = []
  productIdsText.value = ''
  importCategory.value = ''
  importCount.value = 10
  importSortBy.value = 'sales'
}

// 批量设置相关
function openBatchSettingsDialog() {
  batchSettingsDialogVisible.value = true
  batchTarget.value = 'selected'
  batchSettings.value = ['sort', 'status']
  sortMethod.value = 'fixed'
  fixedSortValue.value = 1
  incrementStartValue.value = 1
  incrementStep.value = 1
  batchStatus.value = 'enabled'
}

function confirmBatchSettings() {
  if (!currentRecommend.value) return
  
  const productsToUpdate: RecommendProduct[] = []
  
  if (batchTarget.value === 'selected') {
    if (selectedProductIds.value.length === 0) {
      alert('请先选择要设置的商品')
      return
    }
    productsToUpdate.push(...currentProducts.value.filter(p => selectedProductIds.value.includes(p.id)))
  } else {
    productsToUpdate.push(...currentProducts.value)
  }

  productsToUpdate.forEach(product => {
    if (batchSettings.value.includes('sort')) {
      if (sortMethod.value === 'fixed') {
        product.sort = fixedSortValue.value
      } else if (sortMethod.value === 'increment') {
        product.sort = incrementStartValue.value + incrementStep.value * (product.sort - 1)
      } else if (sortMethod.value === 'random') {
        product.sort = Math.floor(Math.random() * 100) + 1 // 随机排序
      }
    }
    if (batchSettings.value.includes('status')) {
      product.status = batchStatus.value as 'enabled' | 'disabled'
    }
  })

  recommendProducts.value[currentRecommend.value.id] = productsToUpdate
  currentProducts.value = productsToUpdate
  batchSettingsDialogVisible.value = false
  alert('批量设置成功！')
}

// 模板管理弹窗相关
const templateDialogVisible = ref(false)
const templateTab = ref('my') // 'my' | 'system'
const myTemplates = ref([
  {
    id: 't1',
    name: '模板1',
    description: '模板描述1',
    position: '首页轮播图',
    style: '轮播图',
    productCount: 5,
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 't2',
    name: '模板2',
    description: '模板描述2',
    position: '分类页推荐',
    style: '列表',
    productCount: 10,
    createTime: '2024-01-14 14:20:00'
  },
  {
    id: 't3',
    name: '模板3',
    description: '模板描述3',
    position: '详情页相关推荐',
    style: '网格',
    productCount: 8,
    createTime: '2024-01-13 09:15:00'
  },
  {
    id: 't4',
    name: '模板4',
    description: '模板描述4',
    position: '搜索页推荐',
    style: '网格',
    productCount: 6,
    createTime: '2024-01-12 16:45:00'
  }
])
const systemTemplates = ref([
  {
    id: 's1',
    name: '系统模板1',
    description: '系统模板描述1',
    position: '首页轮播图',
    style: '轮播图',
    productCount: 5,
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 's2',
    name: '系统模板2',
    description: '系统模板描述2',
    position: '分类页推荐',
    style: '列表',
    productCount: 10,
    createTime: '2024-01-14 14:20:00'
  },
  {
    id: 's3',
    name: '系统模板3',
    description: '系统模板描述3',
    position: '详情页相关推荐',
    style: '网格',
    productCount: 8,
    createTime: '2024-01-13 09:15:00'
  },
  {
    id: 's4',
    name: '系统模板4',
    description: '系统模板描述4',
    position: '搜索页推荐',
    style: '网格',
    productCount: 6,
    createTime: '2024-01-12 16:45:00'
  }
])

// 保存模板弹窗相关
const saveTemplateDialogVisible = ref(false)
const templateForm = ref({
  name: '',
  description: '',
  includes: ['basic', 'products', 'rules'],
  category: 'home'
})






</script>

<style scoped>
.recommend-manage-root {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.recommend-header {
  background: #fff;
  padding: 20px 24px;
  border-radius: 8px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recommend-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.recommend-subtitle {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.recommend-section {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 16px;
  overflow: hidden;
}

.section-header {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.section-desc {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.section-actions {
  display: flex;
  align-items: center;
}

.architecture-intro {
  display: flex;
  gap: 24px;
  margin-top: 16px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.intro-item {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.intro-icon {
  font-size: 24px;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.intro-text h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.intro-text p {
  margin: 0;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.scenario-demo {
  padding: 20px;
}

.scenario-item {
  margin-bottom: 24px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.scenario-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.scenario-header h4 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.scenario-content {
  display: flex;
  gap: 24px;
}

.strategy-list {
  flex: 1;
}

.strategy-item {
  background: #fff;
  padding: 16px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.strategy-info {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
}

.strategy-name {
  font-weight: 600;
  color: #333;
}

.strategy-priority {
  color: #409eff;
  font-weight: 500;
}

.strategy-type {
  color: #67c23a;
  font-weight: 500;
}

.strategy-desc {
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

.demo-result {
  flex: 1;
  background: #fff;
  padding: 16px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.result-title {
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
}

.result-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-scenario {
  display: flex;
  gap: 8px;
  align-items: center;
}

.user-label {
  font-weight: 500;
  color: #666;
  min-width: 120px;
}

.user-result {
  color: #409eff;
  font-weight: 500;
}

.recommend-actions {
  display: flex;
  align-items: center;
}

.recommend-content {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
}

.edit-form {
  padding: 0 20px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

/* 商品配置样式 */
.product-config {
  padding: 0 20px;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.config-info h4 {
  margin: 0 0 8px 0;
  color: #333;
}

.config-info p {
  margin: 0;
  color: #666;
}

.config-actions {
  display: flex;
  gap: 12px;
}

/* 商品选择器样式 */
.product-selector {
  padding: 0 20px;
}

.selector-search {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 20px;
}

.product-item {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  position: relative;
  transition: all 0.3s;
}

.product-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.product-item.selected {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.product-item img {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 8px;
}

.product-info {
  text-align: center;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  font-size: 16px;
  font-weight: 600;
  color: #f56c6c;
}

.product-check {
  position: absolute;
  top: 8px;
  right: 8px;
}

.selector-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 16px;
  border-top: 1px solid #eee;
}

.selected-count {
  color: #666;
}

.selector-actions {
  display: flex;
  gap: 12px;
}

/* 推荐规则样式 */
.rule-config {
  padding: 0 20px;
}

.rule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.rule-header h4 {
  margin: 0;
  color: #333;
}

.rule-list {
  max-height: 500px;
  overflow-y: auto;
}

.rule-item {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.rule-item .rule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.rule-info {
  display: flex;
  align-items: center;
}

.rule-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.rule-conditions {
  padding-top: 12px;
}

.condition-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.condition-header span {
  font-weight: 500;
  color: #333;
}

.condition-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding: 8px;
  background: #f9f9f9;
  border-radius: 4px;
}

/* 高级规则样式 */
.rule-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-weight: 500;
  color: #333;
}

.time-range-config {
  padding: 12px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.time-inputs {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.days-of-week {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.user-group-config {
  padding: 12px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.custom-user-rules {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
}

.user-condition-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding: 8px;
  background: #f9f9f9;
  border-radius: 4px;
}

.behavior-rule-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding: 12px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.behavior-rule-item span {
  color: #666;
  font-size: 14px;
}

/* 规则测试结果样式 */
.test-results {
  max-height: 300px;
  overflow-y: auto;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  margin-top: 16px;
}

.test-result-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 8px;
  background: #fff;
  border-radius: 4px;
  border-left: 4px solid #67c23a;
}

.test-result-item.failed {
  border-left-color: #f56c6c;
}

.test-result-details {
  margin-top: 8px;
  padding-left: 16px;
  font-size: 12px;
  color: #666;
}

.test-result-details span {
  margin-right: 16px;
}

/* 批量导入样式 */
.batch-import {
  padding: 0 20px;
}

.import-methods {
  margin-bottom: 20px;
}

.excel-import {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.excel-import:hover {
  border-color: #409eff;
}

.excel-import .el-upload__text {
  color: #909399;
}

.excel-import .el-upload__tip {
  color: #909399;
  font-size: 12px;
}

.template-download {
  margin-top: 15px;
}

.ids-import {
  margin-bottom: 20px;
}

.ids-import .el-textarea {
  margin-bottom: 10px;
}

.ids-import .import-tips {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.ids-import .import-tips p {
  margin: 0 0 5px 0;
}

.ids-import .import-tips ul {
  padding-left: 20px;
  margin: 0;
}

.ids-import .import-tips li {
  list-style: disc;
  margin-bottom: 3px;
}

.category-import {
  margin-bottom: 20px;
}

.category-import .el-select {
  margin-bottom: 10px;
}

.category-import .el-input-number {
  margin-bottom: 10px;
}

.import-preview {
  color: #606266;
  font-size: 14px;
  padding: 10px 0;
  border-top: 1px solid #eee;
}

/* 批量设置样式 */
.batch-settings {
  padding: 0 20px;
}

.settings-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.settings-section h4 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 16px;
}

.settings-section .el-radio-group {
  margin-bottom: 10px;
}

.selected-count {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.sort-settings {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.sort-settings .el-radio-group {
  margin-left: 15px;
}

.setting-input {
  margin-left: 15px;
}

.setting-input .el-input-number {
  width: 120px;
}

.setting-input .el-input-number + .el-input-number {
  margin-left: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .rule-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .condition-item,
  .user-condition-item,
  .behavior-rule-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .time-inputs {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .days-of-week {
    flex-direction: column;
    align-items: flex-start;
  }
}

/* 拖拽排序样式 */
.drag-handle {
  cursor: move;
  color: #999;
  text-align: center;
}

.drag-handle:hover {
  color: #409eff;
}

.product-row-0,
.product-row-1,
.product-row-2,
.product-row-3,
.product-row-4,
.product-row-5,
.product-row-6,
.product-row-7,
.product-row-8,
.product-row-9 {
  cursor: move;
}

.product-row-0:hover,
.product-row-1:hover,
.product-row-2:hover,
.product-row-3:hover,
.product-row-4:hover,
.product-row-5:hover,
.product-row-6:hover,
.product-row-7:hover,
.product-row-8:hover,
.product-row-9:hover {
  background-color: #f0f9ff;
}

/* 拖拽时的样式 */
.el-table__row.dragging {
  opacity: 0.5;
  background-color: #f0f9ff;
}

.el-table__row.drag-over {
  border-top: 2px solid #409eff;
}

/* 推荐预览样式 */
.preview-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.preview-info h4 {
  margin: 0 0 8px 0;
  color: #333;
}

.preview-info p {
  margin: 0;
  color: #666;
}

.preview-actions {
  display: flex;
  gap: 12px;
}

.preview-content {
  margin-bottom: 20px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
  overflow-x: auto;
}

/* 轮播图样式预览 */
.preview-carousel {
  position: relative;
  width: 100%;
  height: 200px; /* 固定高度 */
  overflow: hidden;
  border-radius: 8px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.carousel-container {
  display: flex;
  transition: transform 0.5s ease-in-out;
}

.carousel-item {
  min-width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.carousel-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.carousel-info {
  position: absolute;
  bottom: 10px;
  left: 10px;
  color: #fff;
  background: rgba(0, 0, 0, 0.5);
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 14px;
}

.carousel-info h5 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
}

.carousel-info .price {
  font-size: 18px;
  font-weight: 700;
  color: #fff;
}

.carousel-dots {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
}

.carousel-dots .dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: background-color 0.3s;
}

.carousel-dots .dot.active {
  background-color: #fff;
}

/* 列表样式预览 */
.preview-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.list-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 12px 15px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.list-item img {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
}

.list-item .item-info {
  flex-grow: 1;
}

.list-item .item-info h5 {
  margin: 0 0 4px 0;
  font-size: 15px;
  color: #333;
}

.list-item .item-info .price {
  font-size: 16px;
  font-weight: 600;
  color: #f56c6c;
}

/* 网格样式预览 */
.preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 12px;
}

.grid-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.grid-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.grid-item .item-info {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  padding: 8px 10px;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
  color: #fff;
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
}

.grid-item .item-info h5 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
}

.grid-item .item-info .price {
  font-size: 15px;
  font-weight: 700;
  color: #fff;
}

.preview-footer {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding-top: 16px;
  border-top: 1px solid #eee;
}

.preview-stats {
  font-size: 14px;
  color: #666;
}

.mobile-tips {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 12px;
  border-left: 4px solid #409eff;
}

.mobile-tips p {
  margin: 0 0 8px 0;
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.mobile-tips ul {
  margin: 0;
  padding-left: 16px;
}

.mobile-tips li {
  margin-bottom: 4px;
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

/* 模板管理样式 */
.template-manage {
  padding: 0 20px;
}

.template-header {
  margin-bottom: 20px;
}

.template-list {
  max-height: 400px;
  overflow-y: auto;
}

.template-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  margin-bottom: 12px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  transition: all 0.3s;
}

.template-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.template-info {
  flex: 1;
}

.template-info h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
}

.template-info p {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
}

.template-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #999;
}

.template-meta span {
  display: flex;
  align-items: center;
}

.template-actions {
  display: flex;
  gap: 8px;
}

.save-template {
  padding: 0 20px;
}

.save-template .form-item {
  margin-bottom: 20px;
}

.save-template .form-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.save-template .el-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 表单提示样式 */
.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  line-height: 1.4;
}

/* 数据源配置样式 */
.data-source-config {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 16px;
  background: #fafafa;
}

.data-source-detail {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
}

.source-info h5 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.source-info p {
  margin: 0 0 16px 0;
  color: #666;
  font-size: 12px;
  line-height: 1.4;
}

.behavior-config,
.activity-config,
.hot-config,
.manual-config {
  margin-bottom: 16px;
  padding: 12px;
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.behavior-config h6,
.activity-config h6,
.hot-config h6,
.manual-config h6 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 13px;
  font-weight: 600;
}

.time-range-config {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.activity-priority {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.hot-criteria {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.selected-products {
  margin-top: 8px;
  padding: 8px;
  background: #f0f9ff;
  border-radius: 4px;
  border: 1px solid #bae6fd;
}

.selected-products p {
  margin: 0;
  color: #0369a1;
  font-size: 12px;
}

.data-source-test {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
  display: flex;
  gap: 8px;
}

/* 数据源管理样式 */
.data-source-manage {
  padding: 0;
}

.ds-tabs {
  min-height: 400px;
}

.ds-content {
  padding: 16px 0;
}

.ds-content h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.ds-content p {
  margin: 0 0 20px 0;
  color: #666;
  font-size: 14px;
  line-height: 1.4;
}

.ds-config-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid #409eff;
}

.ds-config-section h5 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.ds-config-section p {
  margin: 0 0 12px 0;
  color: #666;
  font-size: 12px;
  line-height: 1.4;
}

/* 活动表单样式 */
.activity-form {
  padding: 0;
}

.activity-products {
  margin-top: 8px;
}

.selected-products-list {
  margin-top: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.selected-products-list p {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 12px;
  font-weight: 600;
}

/* H5手机端预览样式 */
.h5-preview-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.preview-info h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 18px;
}

.preview-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.preview-actions {
  display: flex;
  gap: 8px;
}

.mobile-preview {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.mobile-frame {
  width: 375px;
  min-height: 500px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  border: 1px solid #e0e0e0;
  position: relative;
  transition: transform 0.1s ease;
}

/* 下拉刷新指示器 */
.pull-refresh-indicator {
  position: absolute;
  top: -60px;
  left: 0;
  right: 0;
  height: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0.9), transparent);
  transition: transform 0.3s ease;
  z-index: 10;
}

.refresh-icon {
  font-size: 20px;
  margin-bottom: 4px;
  animation: spin 1s linear infinite;
}

.refresh-text {
  font-size: 12px;
  color: #666;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 轮播图样式 */
.mobile-carousel {
  position: relative;
  height: 200px;
  overflow: hidden;
  touch-action: pan-y pinch-zoom;
}

.carousel-container {
  position: relative;
  height: 100%;
  cursor: grab;
}

.carousel-container:active {
  cursor: grabbing;
}

.carousel-item {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.carousel-item.active {
  opacity: 1;
}

.carousel-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.carousel-overlay {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
  color: #fff;
  padding: 16px;
}

.carousel-overlay h3 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
}

.carousel-overlay .price {
  margin: 0;
  font-size: 18px;
  font-weight: 700;
}

.carousel-dots {
  position: absolute;
  bottom: 8px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 6px;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: background 0.3s;
}

.dot.active {
  background: #fff;
}

/* 列表样式 */
.mobile-list {
  padding: 16px;
}

.mobile-list .list-item {
  display: flex;
  gap: 12px;
  padding: 12px;
  margin-bottom: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  transition: all 0.2s ease;
  cursor: pointer;
}

.mobile-list .list-item:hover {
  background: #e9ecef;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.mobile-list .list-item:active {
  transform: translateY(0);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.mobile-list .list-item:last-child {
  margin-bottom: 0;
}

.mobile-list .list-item img {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  object-fit: cover;
}

.mobile-list .item-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.mobile-list .item-content h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  line-height: 1.3;
}

.mobile-list .item-content .price {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 700;
  color: #ff6b35;
}

.mobile-list .item-content .sort {
  margin: 0;
  font-size: 12px;
  color: #666;
}

/* 网格样式 */
.mobile-grid {
  padding: 16px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.mobile-grid .grid-item {
  background: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e9ecef;
  transition: all 0.2s ease;
  cursor: pointer;
}

.mobile-grid .grid-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.mobile-grid .grid-item:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.mobile-grid .grid-item img {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.mobile-grid .item-content {
  padding: 8px;
}

.mobile-grid .item-content h4 {
  margin: 0 0 4px 0;
  font-size: 12px;
  font-weight: 600;
  color: #333;
  line-height: 1.3;
}

.mobile-grid .item-content .price {
  margin: 0;
  font-size: 14px;
  font-weight: 700;
  color: #ff6b35;
}

/* 空状态样式 */
.empty-preview {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #999;
  text-align: center;
}

.empty-preview .empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-preview h3 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #666;
}

.empty-preview p {
  margin: 0;
  font-size: 14px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .template-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .template-meta {
    flex-direction: column;
    gap: 4px;
  }
  
  .template-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .mobile-frame {
    width: 100%;
    max-width: 375px;
  }
  
  .mobile-grid {
    grid-template-columns: 1fr;
  }
  
  .h5-preview-container {
    padding: 0 10px;
  }
  
  .preview-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .preview-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style> 